import pandas as pd
import numpy as np
import re

def score_professional_knowledge(dialogue_df, resume_text):
    keywords = re.findall(r"\b\w+\b", resume_text.lower())
    matched = sum(any(k in str(answer).lower() for k in keywords) for answer in dialogue_df["我（用户）"])
    return min(100, matched / len(dialogue_df) * 100)

def score_skill_match(dialogue_df, resume_text):
    skills = ["Python", "SQL", "深度学习", "项目管理", "算法", "数据分析"]
    matched = sum(any(skill.lower() in str(answer).lower() for skill in skills) for answer in dialogue_df["我（用户）"])
    return min(100, matched / len(dialogue_df) * 100)

def score_communication(dialogue_df):
    total_len = sum(len(str(a)) for a in dialogue_df["我（用户）"])
    avg_len = total_len / len(dialogue_df)
    return min(100, avg_len * 1.5)

def score_logical_thinking(dialogue_df):
    follow_keywords = ["因为", "所以", "例如", "比如", "首先", "其次", "最后"]
    count = sum(any(word in str(a) for word in follow_keywords) for a in dialogue_df["我（用户）"])
    return min(100, count / len(dialogue_df) * 100)

def score_stress_tolerance(emotion_df):
    sadness_scores = emotion_df[emotion_df["主导情绪"] == "伤心"]["百分比"].astype(float)
    if sadness_scores.empty:
        return 90
    max_sad = sadness_scores.max()
    avg_sad = sadness_scores.mean()
    penalty = max(0, (avg_sad + max_sad) / 2 - 30)
    return max(0, 100 - penalty)

def evaluate_all(resume_text, dialogue_path, emotion_path):
    dialogue_df = pd.read_excel(dialogue_path)
    emotion_df = pd.read_excel(emotion_path)

    scores = {
        "专业知识水平": score_professional_knowledge(dialogue_df, resume_text),
        "技能匹配度": score_skill_match(dialogue_df, resume_text),
        "语言表达能力": score_communication(dialogue_df),
        "逻辑思维能力": score_logical_thinking(dialogue_df),
        "应变抗压能力": score_stress_tolerance(emotion_df)
    }

    return scores, dialogue_df, emotion_df
